
<template>
    <input type="file">

    <img height="500">
</template>
  
<script setup>
import { onMounted } from "vue"

onMounted(() => {
    const input = document.querySelector('input')
    const img = document.querySelector('img')

    input.onchange = (e) => {
        const file = e.target.files[0]
        const type = file.type

        toBase64URL(file).then(url => {
            compressUrl(url, type, 0.8).then(url => {
                img.src = url
            })
        })
    }
})

const toBase64URL = (file) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    // reader.readAsArrayBuffer(file)
    // reader.readAsText(file) //读取文本

    return new Promise(resolve => {
        reader.onload = (e) => {
            console.log(e.target.result);
            const base64URL = e.target.result
            resolve(base64URL)
        }
    })
}

const compressUrl = (imgUrl, type, quality) => {
    const _img = document.createElement('img')
    const _canvas = document.createElement('canvas')
    const canvasCxt = _canvas.getContext('2d')

    _img.src = imgUrl
    return new Promise(resolve => {
        _img.onload = () => {
            const _imgWidth = _img.width
            const _imgHeight = _img.height
            _canvas.width = _imgWidth
            _canvas.height = _imgHeight

            canvasCxt.drawImage(_img, 0, 0, _imgWidth, _imgHeight)

            // toDataURL方式
            const dataURL = _canvas.toDataURL(type, quality)
            resolve(dataURL)

            // toBlob方式
            // _canvas.toBlob((blob) => {
            //     const url = URL.createObjectURL(blob)
            //     resolve(url)
            //     // URL.revokeObjectURL(url) //需要在img onload之后执行销毁
            // }, type, quality)

        }
    })
}
</script>

<style scoped lang="scss">
</style>